package cn.zwx.activiti.example.security;

import cn.hutool.core.bean.BeanUtil;
import cn.zwx.activiti.example.common.ResponseEntry;
import cn.zwx.activiti.example.model.po.UserPO;
import cn.zwx.activiti.example.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功1");

    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功2");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        UserPO userPO = userService.selectUserByUserName(authentication.getName());
        userPO.setPassword(null);
        userPO.setOptPassword(null);
        userPO.setSalt(null);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userPO, true, true);
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(
                ResponseEntry.ok(
                        stringObjectMap
                )));
    }
}
